package org.barman.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;

import org.barman.dao.UserDAO;
import org.barman.exception.CustomMessageException;
import org.barman.exception.ValidationException;
import org.barman.pojo.User;

@WebServlet("/LoginServlet")
public class LoginServlet extends ExceptionHandlingHttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doExceptionHandledPost(HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
			throws ServletException, IOException, CustomMessageException {

		String name = request.getParameter("username");
		String pass = request.getParameter("password");

		UserDAO userDAO = new UserDAO();
		User currentUser = userDAO.getByUsernameAndPassword(name, pass);

		if (currentUser != null) {
			request.getSession().setAttribute("loggedUser", currentUser);
			response.sendRedirect(currentUser.getRole().getName() + "/main.jsp");
		} else {
			throw new ValidationException("Wrong username and/or password");
		}

	}
}
